<?php

include_once "Controller.php";
include_once "models/Track.php";
include_once "models/Tags.php";
include_once "controllers/Artist.php";
include_once "controllers/Release.php";
include_once "controllers/Article.php";
include_once "lib/WebServices/MusicBrainz.php";

class Track extends Controller {
  
  private $artist_name, $release_title, $mb;
  
  public function Track($attr=null){ 
    $this->model = new Track_($attr);
    $this->fe = new FormElements();
    $this->mb = new MusicBrainz(8);
  }
  
  public function add(){
  	
    //check the user input
    $this->checkInput('artist',array(1,200),1);
    $this->checkInput('title',array(1,200),1);
    $this->checkInput('url',null,null,"/^http:\/\/([a-z0-9_\.%-])+\.[a-z]{2,4}\/([a-z0-9_\[\]\.%~\/,?-])+\.mp3$/i");

    if($this->getAttribute('mb_rel_id') == null) {//forced track insertion
        //nicely format the user input of artist and song title
        $attr = array(artist=> $this->uword($this->getAttribute('artist')),
                      title => $this->uword($this->getAttribute('title')));
        //update the model with the formatted attributes
        $this->set($attr);
    }
    else{
      $this->checkInput('release',array(1,200),1);
      $this->checkInput('mb_id',array(36,36));
      $this->checkInput('mb_rel_id',array(36,36));
      $this->checkInput('mb_artist_id',array(36,36));      
    }
    
    if ($this->fe->areThereErrors())
      throw new MTException('INPUT ERROR');   
    
    $release_id = $this->insertRelease($this->insertArtist());
 
    $article_body = $this->getAttribute('article');
        
    //delete the column that aren't in the mt_track table
    $this->set(array('artist'=>null,'mb_artist_id'=>null, 
               'article'=>null, 'mb_rel_id'=>null,'release'=> null));
        
    parent::add();
    $artcle_id = $this->insertArticle($article_body);
    $this->getTags();
    
    return $this;
  }
  
  private function insertArtist(){
  	$this->artist_name = $this->getAttribute('artist');
    $mb_artist_id = $this->getAttribute('mb_artist_id');
    
    //See if we have the artist
    $artist = $mb_artist_id==null?new Artist(array(name=>$this->artist_name)):new Artist(array(mb_id=>$mb_artist_id));
    
    if($artist->get()->id())
      $this->setAttribute('artist_id', $artist->id());
                                                                   
    else { //no? Add one then
      $artist->set(array(name=>$this->artist_name,mb_id=>$mb_artist_id, time_added=>'NOW()'));
      $this->setAttribute('artist_id', $artist->add()->id());       
    }
    
    return $artist->id();
  }
  
  private function insertRelease($artist_id){
  	$this->release_title = $this->getAttribute('release');
    $mb_rel_id = $this->getAttribute('mb_rel_id');
    
    if(!$this->release_title || $this->release_title == 'null') {
      $this->setAttribute('release_id',null);
      return null;
    }
    
    //See if we have the release
    $release = $mb_rel_id == null?new Release(array(title=>$this->release_title)):new Release(array(mb_id=>$mb_rel_id));
      
    if($release->get()->id())
      $this->setAttribute('release_id', $release->id());
      
    else { //no? Add one then
      $release->set(array(title=>$this->release_title,artist_id=>$artist_id,time_added=>'NOW()'));
      $this->setAttribute('release_id', $release->add()->id());
    }
    
    return $release->id();
  }
  
  private function getTags() {
  	/*
     * fetch the toptags for the track from Last.fm
     */
    try{
      $this->mb->setMethod('tags');
      $tags = $this->mb->search($this->artist_name, $this->release_title)->getTags();
       
      if($tags){
        $theTags = new Tags_($tags);
        $theTags->add($this->id);
      }
    }catch(MTException $e){  }
    
  }
  
  public function getCoverArt(){
    
    if($this->result()->coverimage != null || $this->result->release_title == null 
      || $this->result->release_id == null){
      
      return;
    }
    // get artist picture from last.fm
    
    $this->mb->setMethod('release_img');
    try{
      $img_url = $this->mb->search($this->result->artist, $this->result->release_title)->getReleaseImg();
      if(stristr($img_url,'noimage/')) $img_url = null; 
      $image_searched = true;
    }
    catch(MTException $e){ 
      echo('WARNING: '.$e->getMessage()); 
    }
    
    if(isset($image_searched)){
      $release = new Release(array(id=>$this->result->release_id));
      $release->update(array(coverimage=>($img_url?$img_url:'NO_IMAGE')));
      $this->result->coverimage = $img_url?$img_url:'NO_IMAGE';
    }
  }
  
  private function insertArticle($body){
  	//add the corresponding article
    if(isset($body)){
      try { 
        $article = new Article(array(track_id=>$this->model->id, body=>$body));
        $article->add();
      }
      catch(MTException $e){
        if($e->getMessage() == 'INPUT ERROR')
          throw new MTException($article->getInputErrors());
        else throw $e;
      }  
      return $article->result();
    }
    return null;
  }
    
  public function getLink(){
  	if(!isset($this->result))
      return null;
    $uid = Session::factory()->getUserId();
    if ($this->result->submitter == $uid )
      return $this->result->url;
    if(!isset($facebook))
      $facebook = new Facebook(FB_APPKEY, FB_APPSECRET);
    $fb_friends = $facebook->api_client->friends_areFriends(array($_SESSION['fb_info']['uid']), array($this->result->fb_submitter));
    if ($fb_friends['are_friends'])
      return $this->result->url;
  }

}

?>
